package october;

import java.util.Stack;

public class ParenthesisChecker {
    private static final String openBrackets = "({[";
    private static final String closeBrackets = ")}]";

    public static void main(String[] args) {
        String s = "(({[]{}}))";
        System.out.println("Is this string < " + s + " > balanced? " + isBalanced(s));
    }

    private static boolean isBalanced(String s) {
        if (s == null) return false;
        Stack<Character> stack = new Stack<Character>();
        return isBalanced(s, stack);
    }

    private static boolean isBalanced(String s, Stack<Character> stack) {
        if (s.isEmpty()) return stack.isEmpty();
        final char currentChar = s.charAt(0);
        if (isOpenChar(currentChar)) {
            stack.push(currentChar);
            return isBalanced(s.substring(1), stack);
        } else {
            if (isCloseChar(currentChar)) {
                return !stack.isEmpty() && isMatching(stack.pop(), currentChar) && isBalanced(s.substring(1), stack);
            } else return false; // Invalid character found
        }

    }

    private static boolean isMatching(char c1, char c2) {
        return openBrackets.indexOf(c1) == closeBrackets.indexOf(c2);
    }

    private static boolean isOpenChar(char currentChar) {
        return (openBrackets.indexOf(currentChar) > -1);
    }

    private static boolean isCloseChar(char currentChar) {
        return (closeBrackets.indexOf(currentChar) > -1);
    }
}
